package com.db;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class DBConn {
    Connection con = null;
    Statement stmt = null;

    public DBConn() {
        try {
            //Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver");
            Class.forName("com.mysql.cj.jdbc.Driver");
            //Class.forName("oracle.jdbc.driver.OracleDriver");
            //建立连接
            //con = DriverManager.getConnection("jdbc:microsoft:sqlserver://127.0.0.1:1433;databasename=student","sa","");
            con = DriverManager.getConnection("jdbc:mysql://localhost:3306/sams?characterEncoding=utf-8", "root", "@yj730721");
            //con = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:ora90","java1","java1");
            //执行
            stmt = con.createStatement();
        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    //查询方法
    public ResultSet queryData(String sql) throws SQLException {

        if (stmt != null) {
            //System.out.print("执行");
            return stmt.executeQuery(sql);
        } else return null;
    }

    /**
     * 执行SQL语句
     *
     * @param sql SQL语句
     */
    public void updateData(String sql) throws SQLException {
        if (stmt != null)
            stmt.executeUpdate(sql);
    }


    public void setAutoCommit(boolean tjzt) throws SQLException {
        con.setAutoCommit(tjzt);
    }

    /**
     * 提交数据
     */
    public void commit() throws SQLException {
        con.commit();
    }

    /**
     * 回滚数据
     */
    public void rollback() throws SQLException {
        con.rollback();
    }

    /**
     * 关闭连接
     */
    public void close() throws Exception {
        if (stmt != null) {
            stmt.close();
            stmt = null;
        }
        if (stmt != null) {
            stmt.close();
            stmt = null;
        }
    }
}
